package labuladong.动态规划;

import java.util.Arrays;

/**
 * 字集背包问题
 */
public class Demo03 {
    public static void main(String[] args) {
        int[] nums = {1, 5, 11, 5};
        System.out.println(canPartition2(nums));
    }

    public static boolean canPartition(int[] nums) {
        int sum = 0;
        for (int num : nums){
            sum = sum + num;
        }
        if (sum % 2 != 0)
            return false;
        int n = nums.length;
        boolean[][] dp = new boolean[n+1][sum/2 + 1];
        for(int m=0; m<=n; m++){
            Arrays.fill(dp[m], false);
        }

        for(int k=0; k<=n; k++)
            dp[k][0] = true;

        for(int i=1; i<=n; i++){
            for(int j=1; j<= sum/2; j++) {
                if(j - nums[i-1] < 0)
                    dp[i][j] = dp[i-1][j];
                else
                    dp[i][j] = dp[i-1][j] | dp[i-1][j-nums[i-1]];
            }
        }
        return dp[n][sum/2];
    }

    public static boolean canPartition2(int[] nums) {
        int sum = 0;
        for (int num : nums){
            sum = sum + num;
        }
        if (sum % 2 != 0)
            return false;
        int n = nums.length;
        boolean[] dp = new boolean[sum/2 +1];
        Arrays.fill(dp,false);
        dp[0] = true;

        for(int i=0; i<n; i++) {
            for(int j=sum/2; j>=0; j--){
                if(j - nums[i] >= 0) {
                    dp[j] = dp[j] || dp[j-nums[i]];
                }
            }
        }
        return dp[sum/2];
    }
}
